package org.gas.barapraja.handler;

import org.apache.log4j.Logger;
import org.gas.barapraja.db.dao.AccountDao;
import org.gas.barapraja.db.dao.MessageDao;
import org.gas.barapraja.db.entity.Account;
import org.gas.barapraja.db.entity.Message;
import org.gas.barapraja.handler.validator.RequestValidator;
import org.gas.barapraja.proc.PduProcessor;
import org.gas.barapraja.proc.buffer.AppQueuePool;
import org.gas.barapraja.proc.buffer.MsgQueue;
import org.gas.barapraja.util.GasAppContext;

import com.logica.smpp.pdu.SubmitSM;
import com.logica.smpp.pdu.SubmitSMResp;
import com.logica.smpp.pdu.WrongLengthOfStringException;

public class SingleMsgHandler extends RequestHandlerAdapter {
	
	private static final Logger logger=Logger.getLogger(SingleMsgHandler.class);
	
	private MessageComposer composer;
	
	private TokenDetails tokenDetails;
	
	public SingleMsgHandler(PduProcessor pduProcessor) {
		super();
		setPduProcessor(pduProcessor);
		composer=new MessageComposer();
		tokenDetails=new AccountTokenDetails();
	}

	@Override
	public int handleRequest(SubmitSM submitSM) {
		int status=validator.validate(submitSM);
		try {
			if(status==RequestValidator.TOKEN_OK){
				logger.info("message token status OK. composing submit sm request...");
				Message message=composer.compose(submitSM);
				logger.info("message composed: "+message.toString());
				MessageDao messageDao=GasAppContext.springConfiguredBean(MessageDao.class);
				logger.info("saving message to database");
				AccountDao accountDao=GasAppContext.springConfiguredBean(AccountDao.class);
				Account account=accountDao.findByNumber(message.getSource());
				logger.info("update user token from: "+account.getToken().getTokenValue());
				tokenDetails.setAccount(account);
				tokenDetails.decreaseToken(1);
				accountDao.update(account);
				logger.info("token value updated. current token value: "+account.getToken().getTokenValue());
				MsgQueue msgQueue=AppQueuePool.msgQueueInstance();
				msgQueue.queue(message);
				messageDao.persist(message);
				SubmitSMResp resp=(SubmitSMResp) submitSM.getResponse();
				resp.setMessageId(String.valueOf(submitSM.getSequenceNumber()));
				pduProcessor.serverResponse(resp);
			}else{
				logger.info("message token status NOT OK");
				pduProcessor.stop();
			}
		} catch (WrongLengthOfStringException e) {
			e.printStackTrace();
		}
		return status;
	}
	
	

}

